<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> {{ pageTitle }} </view>
      </template>
    </FilterNavbar>
    <ve-form ref="ve_form" :model="form" :rules="rules" style="padding: 24rpx">
      <ve-card title="车辆基本信息" type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item label="车牌号" prop="carId" :borderBottom="false" required>
          <remote-select
            type="licenseNo"
            :label="form.licenseNo"
            @change="changeLicenseNo"
            :disabled="handleFlag != 'add' || handleOrigin == 'short-order' || handleOrigin == 'long-order'"
            :params="{ idList: form.carId ? [form.carId] : undefined, operateStatusList: [10, 20, 30, 40, 50] }"
            v-model="form.carId"
          />
        </ve-form-item>
        <car-info :record="record" :handleFlag="handleFlag" v-if="form.carId" />
      </ve-card>
      <ve-card title="违章信息" type="none" fold v-model:initFold="foldStatus.fold2">
        <ve-form-item label="违章单关联门店" prop="siteId" required>
          <remote-select type="site" v-model="form.siteId" :label="form.siteName" :params="{ oldId: form.siteId }" @change="changeSiteId" />
        </ve-form-item>
        <ve-form-item label="违章时间" prop="eventTime" required>
          <ve-date-picker
            v-model="form.eventTime"
            title="时间"
            :params="datetimeparams"
            :disabled="handleFlag == 'handle' || handleFlag == 'finish'"
          ></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="违章发生方">
          <template #icon v-if="form.existConfirmFee || form.existConfirmCostFee">
            <ve-tooltip placement="top">
              <template #content> 关联的费用已结算，不允许修改 </template>
              <ve-icon name="exclamation-circle-fill" width="36" height="36" />
            </ve-tooltip>
          </template>
          <ve-radio
            :disabled="handleFlag == 'finish' || form.existConfirmFee || form.existConfirmCostFee"
            :list="dict.violationPartyEnum"
            @confirm="violationPartyChange"
            v-model="form.violationParty"
          ></ve-radio>
        </ve-form-item>
        <ve-form-item label="关联订单号">
          <remote-select
            v-model="form.orderId"
            :mustParentTip="mustParentTip"
            type="orderByTimeAndCar"
            :params="{
              carId: form.carId,
              orderTime: form.eventTime,
              dzOrderTime: form.eventTime,
              orderTypeList: [2, 3], // 关联长租\短租
              useAuth: 1,
              oldOrderType: form.orderType,
              oldOrderId: form.orderId,
            }"
            :disabled="handleOrigin == 'short-order' || handleOrigin == 'long-order' || handleFlag == 'finish'"
            :label="form.orderCode"
            @change="orderChange"
          />
        </ve-form-item>
        <ve-form-item label="违章城市">
          <remote-select
            type="city"
            :label="form.eventCityName"
            @change="changeCity"
            v-model="form.eventCityCode"
            :params="{
              oldCityCodes: form.eventCityCode ? [form.eventCityCode] : undefined,
            }"
          />
        </ve-form-item>
        <ve-form-item label="违章地点">
          <ve-input v-model="form.eventAddress" />
        </ve-form-item>
        <ve-form-item label="违章行为">
          <ve-input v-model="form.eventContent" />
        </ve-form-item>
        <ve-form-item label="罚分" unit="分">
          <ve-input-number v-model="form.eventScore" :precision="0" :min="0" :max="100" placeholder="请输入"> </ve-input-number>
        </ve-form-item>
        <!-- 已收款，则不支持修改罚款及代办服务费 -->
        <ve-form-item label="罚款" unit="元">
          <template #icon v-if="form.existConfirmFee">
            <ve-tooltip>
              <template #content>
                <view>费用已结算，如需修改请前往</view>
                <view>流水驳回或撤销费用后，进行修改</view>
              </template>
              <ve-icon name="exclamation-circle-fill" width="36" height="36" />
            </ve-tooltip>
          </template>
          <ve-input-number
            :disabled="handleFlag == 'finish' || form.existConfirmFee"
            :precision="2"
            :min="0"
            :max="99999999.99"
            v-model="form.eventAmount"
          />
        </ve-form-item>
        <!-- 发生方是员工时，处理方仅仅展示员工处理 -->
        <ve-form-item label="处理方" prop="handleType" required>
          <template #icon v-if="form.existConfirmFee || form.existConfirmCostFee">
            <ve-tooltip>
              <template #content> 关联的费用已结算，不允许修改 </template>
              <ve-icon name="exclamation-circle-fill" width="36" height="36" />
            </ve-tooltip>
          </template>
          <ve-radio
            v-if="form.violationParty == 0"
            :disabled="handleFlag == 'finish' || form.existConfirmFee || form.existConfirmCostFee"
            :list="[
              { value: 1, label: '租车公司', disabled: false, desc: undefined },
              { value: 2, label: '客户处理', disabled: false, desc: undefined },
            ]"
            @confirm="radioconfirm"
            v-model="form.handleType"
          ></ve-radio>
          <ve-radio
            v-else
            :disabled="handleFlag == 'finish' || form.existConfirmFee"
            :list="[{ value: 3, label: '员工处理', disabled: false, desc: undefined }]"
            @confirm="radioconfirm"
            v-model="form.handleType"
          ></ve-radio>
        </ve-form-item>
        <view class="form-block">
          <ve-form-item
            label="负责人"
            :prop="handleFlag === 'handle' || handleFlag === 'finish' ? 'staffId' : ''"
            :required="handleFlag === 'handle' || handleFlag === 'finish' ? true : false"
          >
            <remote-select
              type="staff_all_bysite"
              :mustParentTip="mustParentTip1"
              :label="form.staffName"
              v-model="form.staffId"
              :params="{ oldId: form.staffId, siteIdList: [record.siteId] }"
              @change="changeStaff"
            />
          </ve-form-item>
          <!-- 租车公司处理，展示 -->
          <template v-if="form.handleType == 1">
            <ve-form-item label="具体代办方式">
              <!-- <ve-input :disabled="handleFlag == 'handle'" v-model="form.specificHandleWay" /> -->
              <remote-select
                type="specific_way"
                :label="form.specificHandleWayName"
                v-model="form.specificHandleWay"
                :disabled="handleFlag == 'finish'"
                @change="changeSpecificHandleWay"
              />
            </ve-form-item>
            <!-- 已收款，则不支持修改及代办服务费 -->
            <ve-form-item label="代办服务费" unit="元" labelTooltipContent="代办服务费不包含罚款">
              <template #icon v-if="form.existConfirmFee">
                <ve-tooltip placement="top">
                  <template #content>
                    <view>费用已结算，如需修改请前往</view>
                    <view>流水驳回或撤销费用后，进行修改</view>
                  </template>
                  <ve-icon name="exclamation-circle-fill" width="36" height="36" />
                </ve-tooltip>
              </template>
              <ve-input-number
                :precision="2"
                :min="0"
                :max="99999999.99"
                :disabled="form.handleType == 2 || handleFlag == 'finish' || form.existConfirmFee"
                v-model="form.handleAmount"
              >
              </ve-input-number>
            </ve-form-item>
            <ve-form-item label="代办真实成本" unit="元">
              <template #icon v-if="handleFlag == 'edit' && form.existConfirmCostFee">
                <ve-tooltip placement="top">
                  <template #content>
                    <view>费用已结算，如需修改请前往</view>
                    <view>流水驳回或撤销费用后，进行修改</view>
                  </template>
                  <ve-icon name="exclamation-circle-fill" width="36" height="36" />
                </ve-tooltip>
              </template>
              <ve-input-number
                v-model="form.handleRealCost"
                :disabled="handleFlag == 'finish' || (handleFlag == 'edit' && form.existConfirmCostFee)"
                :precision="2"
                :min="0"
                :max="99999999.99"
              />
            </ve-form-item>
          </template>

          <ve-form-item label="违章押金收取方式">
            <ve-picker-inline v-model="form.violationChargeType" :range="dict.inExpWayList" unit="arrowRight" />
          </ve-form-item>
          <ve-form-item label="备注" labelPosition="top">
            <ve-input type="textarea" v-model="form.remark" placeholder="请输入备注" :maxlength="200" />
          </ve-form-item>
          <ve-form-item
            label="上传附件"
            labelPosition="top"
            :borderBottom="false"
            :prop="handleFlag === 'handle' || handleFlag === 'finish' ? 'fileIdList' : ''"
            :required="handleFlag === 'handle' || handleFlag === 'finish'"
          >
            <ve-upload v-model="form.fileIdList"></ve-upload>
          </ve-form-item>
        </view>
        <ve-gap size="24"></ve-gap>
      </ve-card>
      <!-- 行驶证记录: 客户处理、员工处理 -->
      <ve-card v-if="form.handleType != 1" title="行驶证记录" type="none" fold>
        <template v-for="i_form in form.driveLicenseRecordList" :key="i_form.driveLicenseUseState">
          <ve-form-item :label="i_form.label">
            <ve-date-picker v-model="i_form.driveLicenseUseTime" :params="datetimeparams"></ve-date-picker>
          </ve-form-item>
          <ve-form-item :label="i_form.name">
            <ve-radio
              v-model="i_form.depositState"
              :list="[
                { value: 1, label: '是' },
                { value: 2, label: '否' },
              ]"
            ></ve-radio>
          </ve-form-item>
          <ve-form-item label="押金金额" unit="元">
            <ve-input-number v-model="i_form.depositAmount" :precision="2" :min="0" :max="99999999.99" />
          </ve-form-item>
          <ve-form-item label="上传凭证" labelPosition="top" :borderBottom="i_form.driveLicenseUseState == 1">
            <ve-upload v-model="i_form.fileIdList" maxCount="1" @on-remove="(val) => onRemoveFile(i_form, val)"></ve-upload>
          </ve-form-item>
        </template>
      </ve-card>
    </ve-form>

    <ve-bottom-box size="mini">
      <ve-button type="primary" size="long" :loading="saveLoading" @click="handleSave">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { ref, computed, watch } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { usePageDict } from '@/hooks/useDict'
  import CarInfo from './carInfo.vue'
  import { createViolation, getViolationDetail, editViolation, getLinkedOrder } from '@/api/asset/car-violation'
  import { orderCarInfo } from '@/api/asset/car-manager'
  import FilterNavbar from '@/components/FilterNavbar'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { findUserInfo } from '@/api/common'
  import { getDepositType } from '@/api/order/sOrder'
  import { getDepositWay } from '@/api/order/lOrder'

  const userInfo = ref({})
  const dict = usePageDict('carViolationDict')

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['carId'],
    },
    {
      key: 'fold2',
      props: ['siteId','eventTime', 'handleType', 'violationDepositType', 'staffId', 'fileIdList'],
    },
  ])

  const saveLoading = ref(false)
  const DriveLicenseRecordListCreatorFn = () => [
    {
      label: '行驶证借出',
      name: '是否收取押金',
      driveLicenseUseState: 1,
      driveLicenseUseTime: '',
      depositState: null,
      depositAmount: null,
      fileIdList: [],
    },
    {
      label: '行驶证归还',
      name: '是否归还押金',
      driveLicenseUseState: 2,
      driveLicenseUseTime: '',
      depositState: null,
      depositAmount: null,
      fileIdList: [],
    },
  ]
  const form = ref({
    // 违章发生方：承租人
    violationParty: 0,
    // 处理方：租车公司，   1,租车公司 2,客户处理 3,员工处理
    handleType: 1,
    violationDepositType: 2,
    eventTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    // 驾驶证记录，一借一还
    driveLicenseRecordList: DriveLicenseRecordListCreatorFn(),
  })

  const record = ref({
    // 违章费用的状态：1无需收款、2未收款，3已收款
    violationFeeState: 0,
  })
  const rules = ref({
    carId: {
      required: true,
      message: '请选择车牌号',
    },
    siteId: {
      required: true,
      message: '请选择违章单关联门店',
    },
    eventTime: {
      required: true,
      message: '请选择违章时间',
    },
    handleType: {
      required: true,
      message: '请选择处理方',
    },
    violationDepositType: {
      required: true,
      message: '请选择违章费是否支持押金自动抵扣',
    },
    staffId: {
      required: true,
      message: '请选择负责人',
    },
    fileIdList: {
      required: true,
      message: '请上传附件',
    },
  })

  // 必填提示
  const mustParentTip = computed(() => {
    if (!form.value.carId) return '请选择车牌号'
    if (!form.value.eventTime) return '请选择违章时间'
    return ''
  })

  const mustParentTip1 = computed(() => {
    if (!form.value.carId) return '请选择车牌号'
    return ''
  })

  const pageTitle = ref('新增违章')
  // 新增、编辑、处置
  const handleFlag = ref('add')
  const handleOrigin = ref('') // 操作来源
  // 选择车牌号
  const changeLicenseNo = (a, option = {}) => {
    form.value.carId = a
    form.value.licenseNo = option.licenseNo
    form.value.siteId = option.siteId
    form.value.siteName = option.siteName
    form.value.violationChargeType = null
    record.value = option

    if (record.value?.id && form.value.entranceDate) {
      selectLinkedOrder()
    }

    if (!form.value.staffId) {
      form.value.staffId = userInfo.value.employeeId
      form.value.staffName = userInfo.value.realname
    }
  }
  // 发生发change
  const violationPartyChange = (e) => {
    form.value.violationParty = e.value
    // 发生发为员工，处理方设置配员工处理
    if (e.value === 1) {
      form.value.handleType = 3
    } else {
      form.value.handleType = 1
    }
  }

  const onRemoveFile = (item, val) => {
    console.log('onChangeFile', item, val)
    item.fileIdList = val
    item.fileIds = val[0]
  }

  /**
   * 获取短租订单押金收取方式
   */
  const getSorderInExpWayList = (id) => {
    getDepositType({ id }).then((res) => {
      console.log('getSorderInExpWayList: ', res)
      const { violationDepositFee } = res.result
      if (violationDepositFee) {
        if (violationDepositFee.feeStatus == 1) {
          form.value.violationChargeType = -99
        } else {
          const index = dict.inExpWayList.findIndex((item) => item.value == violationDepositFee.payType)
          if (index > -1) {
            form.value.violationChargeType = violationDepositFee.payType
          } else {
            form.value.violationChargeType = null
          }
        }
      }
    })
  }

  /**
   * 获取长租订单押金收取方式
   */
  const getLorderInExpWayList = (id) => {
    getDepositWay({ id }).then((res) => {
      console.log('getLorderInExpWayList: ', res)
      const { violationDepositFee } = res.result
      if (violationDepositFee) {
        if (violationDepositFee.feeStatus == 1) {
          form.value.violationChargeType = -99
        } else {
          const index = dict.inExpWayList.findIndex((item) => item.value == violationDepositFee.payType)
          if (index > -1) {
            form.value.violationChargeType = violationDepositFee.payType
          } else {
            form.value.violationChargeType = null
          }
        }
      }
    })
  }

  // 订单change
  const orderChange = (val, option = {}) => {
    console.log('orderChange', option)
    form.value.orderCode = option.orderNo
    form.value.orderType = option.orderType
  }

  // 自动选中违章订单 before
  watch([() => form.value.carId, () => form.value.eventTime], (val) => {
    // 只有从违章列表新增的来源时使用这个逻辑（长租、短租列表的新增也需要避免这个逻辑）
    if (
      val[0] &&
      val[1] &&
      handleFlag.value != 'handle' &&
      handleFlag.value != 'edit' &&
      handleOrigin.value != 'short-order' &&
      handleOrigin.value != 'long-order'
    ) {
      form.value.orderId = undefined
      form.value.orderCode = undefined
      selectLinkedOrder()
    }
  })
  const selectLinkedOrder = () => {
    getLinkedOrder({
      carId: form.value.carId,
      orderTime: form.value.eventTime,
      dzOrderTime: form.value.eventTime,
      orderTypeList: [2, 3], // 关联长租\短租
      useAuth: 1,
    }).then((res) => {
      if (res.code == 200) {
        const order = res.result[0]
        if (order) {
          form.value.orderId = order.orderId
          form.value.orderCode = order.orderNo
          form.value.orderType = order.orderType
          if (order.orderType == 3 && !order.violationChargeType) {
            getLorderInExpWayList(order.orderId)
          }

          if (order.orderType == 2 && !order.violationChargeType) {
            getSorderInExpWayList(order.orderId)
          }
        }
      }
    })
  }
  // 自动选中违章订单 end

  // 选择城市
  const changeCity = (_, option = {}) => {
    form.value.eventCityCode = option.code
    form.value.eventCityName = option.name
  }
  const changeSpecificHandleWay = (_, option = {}) => {
    form.value.specificHandleWayName = option.name
  }
  // 选择 负责人
  const changeStaff = (_, option = {}) => {
    form.value.staffName = option.realname
  }

  // 选择处理方
  const radioconfirm = () => {
    form.value.handleAmount = undefined
  }

  const ve_form = ref(null)
  const handleSave = () => {
    // 表单验证
    saveLoading.value = true
    ve_form.value.validate((valid, errors) => {
      if (valid) {
        const params = {
          ...form.value,
        }
        let fetch
        if (handleFlag.value == 'edit' || handleFlag.value == 'handle' || handleFlag.value == 'finish') {
          if (handleFlag.value == 'handle') {
            params.eventStatus = 1
          }
          fetch = editViolation
        } else if (handleFlag.value == 'add') {
          fetch = createViolation
        }
        fetch(params)
          .then((res) => {
            saveLoading.value = false
            if (res.code == 200) {
              uni.showToast({
                title: '操作成功',
                icon: 'none',
              })
              uni.$emit('refreshData')
              uni.navigateBack({
                delta: 1,
              })
            } else {
              saveLoading.value = false
              uni.showToast({
                title: res.message,
                icon: 'none',
              })
            }
          })
          .catch(() => {
            saveLoading.value = false
          })
      } else {
        saveLoading.value = false
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }

  const getDetail = async (id) => {
    const res = await getViolationDetail({ id: id })
    if (res.code === 200) {
      const data = res.result
      form.value = data
      // 初始化驾驶证记录
      if (!data.driveLicenseRecordList) {
        data.driveLicenseRecordList = DriveLicenseRecordListCreatorFn()
      } else {
        DriveLicenseRecordListCreatorFn().forEach((item, index) => {
          data.driveLicenseRecordList[index] = {
            ...item,
            ...data.driveLicenseRecordList[index],
          }
        })
      }
      record.value = data
      if ((handleFlag.value == 'end' || handleFlag.value == 'finish' || handleFlag.value === 'handle') && !form.value.staffId) {
        form.value.staffId = userInfo.value.employeeId
        form.value.staffName = userInfo.value.realname
      }
    }
  }

  const datetimeparams = ref({
    year: true,
    month: true,
    day: true,
    hour: true,
    minute: true,
    second: true,
  })

  const getCarOrderInfo = (data, flag) => {
    orderCarInfo({ id: data, type: flag }).then((res) => {
      if (res.code == 200) {
        const result = res.result
        record.value = result
        form.value.carId = result.carId
        form.value.licenseNo = result.licenseNo
        form.value.eventTime = result.startTime
        form.value.orderId = result.orderId
        form.value.orderCode = result.orderCode
        form.value.orderType = result.type
        form.value.siteId = result.siteId
        form.value.siteName = result.siteName
        if (!form.value.staffId) {
          form.value.staffId = userInfo.value.employeeId
          form.value.staffName = userInfo.value.realname
        }

        if (result.type == 3 && !result.violationChargeType) {
          getLorderInExpWayList(result.orderId)
        }

        if (result.type == 2 && !result.violationChargeType) {
          getSorderInExpWayList(result.orderId)
        }
      }
    })
  }

  // 获取员工登录信息
  const getUserInfoApi = () => {
    return new Promise((resolve, reject) => {
      findUserInfo({})
        .then((res) => {
          const data = res.result
          userInfo.value = data
          resolve()
          console.log('userInfo', userInfo.value)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 关联门店
  const changeSiteId = (a, option = {}) => {
    console.log(a)
    console.log(option)
    form.value.siteId = a
    form.value.siteName = option.siteName
  }

  onLoad((record) => {
    console.log(record)
    getUserInfoApi().then(() => {
      if (record.origin == 'edit') {
        pageTitle.value = '编辑违章'
        handleOrigin.value = 'carViolation'
        getDetail(record.id)
        handleFlag.value = 'edit'
      }
      if (record.origin == 'handle') {
        console.log(record.id)
        pageTitle.value = '处理违章'
        handleOrigin.value = 'carViolation'
        getDetail(record.id)
        handleFlag.value = 'handle'
      }
      if (record.origin == 'finish') {
        console.log(record.id)
        pageTitle.value = '处理违章'
        handleOrigin.value = 'carViolation'
        getDetail(record.id)
        handleFlag.value = 'finish'
      }
      if (record.origin == 'operate') {
        pageTitle.value = '新增违章'
        handleFlag.value = 'add'
        handleOrigin.value = 'operate'
        form.value.licenseNo = record.licenseNo
        if (!form.value.staffId) {
          form.value.staffId = userInfo.value.employeeId
          form.value.staffName = userInfo.value.realname
        }
      }
      if (record.origin == 'short-order' || record.origin == 'long-order') {
        pageTitle.value = '新增违章'
        handleOrigin.value = record.origin
        handleFlag.value = 'add'
        if (record.orderId) {
          getCarOrderInfo(record.orderId, record.origin == 'short-order' ? 2 : 3)
        }
      }
    })
  })
</script>

<style lang="scss" scoped>
  .content {
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    padding: 24rpx;
    background: #f7f8fa;
  }
  :deep(.ve-textarea) {
    background: #eff0f2;
  }
  .tip-tag {
    border: 1px solid;
    color: #f53f3f;
    font-size: 26rpx;
    border-radius: 6rpx;
    padding: 4rpx 12rpx;
    margin-top: -24rpx;
  }
</style>
